import widgetlist from './widgetlist'
import filterPropName from './filter-props'
import $config from '@/config'
import {
  ElementModel
} from '@/models/Element'
import {
  SceneModel
} from '@/models/Scene'
import axios from '@/utils/comm-request'
import urls from '@/api'
import {
  getToken
} from '@/utils'
import {
  cloneDeep
} from 'lodash'
import {
  resolve
} from 'path'
import {
  stat
} from 'fs'
import {
  Message
} from 'element-ui';
const state = {
  // 缩放比例
  scaleValue: 0.5,
  // 页面提示
  pageTipShow: '',
  // 页面信息
  pageData: {
    id:'',
    width: $config.canvasPCWidth,
    height: $config.canvasPCHeight,
    programName: '默认名称',
    // TODO
    titlePicUrl: 'http://192.144.132.100:8105/material/1599618080717.jpeg',
    dialog: true
  },
  // 组件列表
  widgetlist,
  // 素材弹层显示
  showMaterial: false,
  showPreview: false,
  // 当前场景
  currSceneUUID: '',
  // 当前选则元素
  currElementUUID: '',
  // 当前选则元素
  currBeforeElement: {},
  currAttrPannelIndex: '0',
  fullBeforeElement: {},
  // 场景list
  scenes: []
}

const getters = {
  currSceneIndex(state) {
    if (!state.scenes || !state.scenes.length || !state.currSceneUUID) {
      return -1
    }
    return state.scenes.findIndex(v => {
      return v.uuid === state.currSceneUUID
    })
  },
  hasCurrScene(state) {
    return getters.currSceneIndex(state) !== -1
  },
  // 当前选中场景
  currScene(state) {
    // 如果不存在页面返回-1
    if (!state.scenes || !state.scenes.length || !state.currSceneUUID) {
      return {
        commonStyle: {},
        config: {}
      }
    }
    return state.scenes.find(v => {
      return v.uuid === state.currSceneUUID
    })
  },
  bgMusicList(state) {
    if (!getters.hasCurrScene(state)) {
      return []
    }
    let list = [];
    const scene = getters.currScene(state);
    if( scene.elements.length > 0 ){
      for ( let i=0,len = scene.elements.length; i<len; i++ ){
        if(scene.elements[i].elName === 'sxc-audio'){
          for(let k=0; k<scene.elements[i].propsValue.bgAudioList.length; k++){
            list.push(scene.elements[i].propsValue.bgAudioList[k]);
          }
        }
      }
    }
    return list;
  },
  // 当前选中元素
  currElement(state) {
    // 如果不存在页面返回-1
    const pidx = getters.currSceneIndex(state)
    if (pidx === -1) {
      return {
        commonStyle: {
          backgrondSize: '100%'
        },
        propsValue: {}
      }
    }
    const elem = state.scenes[pidx].elements.find(v => {
      return v.uuid === state.currElementUUID
    })
    return elem
  },
  currElementIndex(state) {
    if (!getters.hasCurrElement(state)) {
      return -1
    }
    const pidx = getters.currSceneIndex(state)
    return state.scenes[pidx].elements.findIndex(v => {
      return v.uuid === state.currElementUUID
    })
  },
  hasCurrElement(state) {
    const elem = getters.currElement(state)
    return elem && elem.uuid
  },
  hasProps(state) {
    if (!getters.hasCurrElement(state)) {
      return false
    }
    const elem = getters.currElement(state)
    if (!elem.propsValue) return false
    let keys = Object.keys(elem.propsValue)
    keys = keys.filter(item => {
      return item.indexOf(filterPropName) === -1
    })
    return keys.length > 0
  },
  canPlusScale(state) {
    return state.scaleValue < 1.5
  },
  canReduceScale(state) {
    return state.scaleValue > 0.25
  },
  getCurrElementUUID(state){
    return state;
  },
  getliveCurrElement(state){
    const pidx = getters.currSceneIndex(state);
    const res = state.scenes[pidx].elements.find(item=>(item.elName==='sxc-live'));
    return res;
  }
}

const mutations = {
  /**
   * 设置当前选中场景id
   * @param {*} uuid
   */
  setCurrSceneUUID(state, uuid) {
    state.currSceneUUID = uuid
    state.currElementUUID = ''
  },
  /**
   * 设置当前选中元素id
   * @param {*} uuid
   */
  setCurrElementUUID(state, uuid) {
    state.currElementUUID = uuid
  },
  setCurrBeforeElement(state, data){
    state.currBeforeElement = data
  },
  setFullBeforeElement(state, data){
    state.fullBeforeElement[data.uuid] = data.pos;
  },
  /**
   * 设置选中tab名
   * @param {*} val
   */
  setCurrAttrPannelIndex(state, val) {
    state.currAttrPannelIndex = val
  },
  /**
   * 设置素材弹层显隐
   */
  setShowMaterial(state, val) {
    state.showMaterial = val
  },
  setShowPreview(state, val) {
    state.showPreview = val
  },
  // 设置页面提示
  setPageTipShow(state, val) {
    state.pageTipShow = val
  },
  setScaleValue(state, val) {
    if (val < 0.25 || val > 1.5) {
      return
    }
    state.scaleValue = val
  },
  /**
   * 添加场景
   * @param {*} {data, index}
   */
  insertScene(state, {
    data,
    index
  }) {
    if (index) {
      state.scenes.splice(index, 0, data)
    } else {
      state.scenes.push(data)
    }
  },
  /**
   * 删除场景
   * @param {*} uuid
   */
  deleteScene(state, uuid) {
    if (state.scenes.length < 2) {
      Message.warning("场景不能小于一个！")
    } else {
      let pidx = state.scenes.findIndex(v => (v.uuid === uuid))
      state.scenes.splice(pidx, 1)
      let nowToIndex = state.scenes.length - 1;
      state.currSceneUUID = state.scenes[nowToIndex].uuid;
      state.currElementUUID = ''
    }
  },
  /**
   * 当前场景添加元素
   * @param {*} data
   */
  insertElement(state, data) {
    let index = getters.currSceneIndex(state)
    if (index > -1) {
      state.scenes[index].elements.push(data)
    }
  },
  /**
   * 根据id删除元素
   * @param {*} uuid
   */
  deleteElementById(state, uuid) {
    let pidx = getters.currSceneIndex(state)
    let ap = getters.currScene(state)
    let eidx = ap.elements.findIndex(v => (v.uuid === uuid))
    state.scenes[pidx].elements.splice(eidx, 1)
  },
  deleteElementItemById(state, id) {
    let pidx = getters.currSceneIndex(state)
    let ap = getters.currScene(state)
    const {
      currElementUUID
    } = state
    let eidx = ap.elements.findIndex(v => (v.uuid === currElementUUID));
    if(ap.elements[eidx].elName==='sxc-image'){
      let itemIdx = ap.elements[eidx].propsValue.imageSrcList.findIndex(v => (v.id === id))
      state.scenes[pidx].elements[eidx].propsValue.imageSrcList.splice(itemIdx, 1)
      if(state.scenes[pidx].elements[eidx].propsValue.imageSrcList.length<=0){
        mutations.resetElementZIndex(state,{type: 'set0'});
        state.scenes[pidx].elements.splice(eidx, 1);
        state.currElementUUID = '';
      }
    }
  },
  deleteVideoElementItemById(state, id) {
    let pidx = getters.currSceneIndex(state)
    let ap = getters.currScene(state)
    const {
      currElementUUID
    } = state
    let eidx = ap.elements.findIndex(v => (v.uuid === currElementUUID));
    if(ap.elements[eidx].elName==='sxc-video'){
      let itemIdx = ap.elements[eidx].propsValue.videoList.findIndex(v => (v.id === id))
      state.scenes[pidx].elements[eidx].propsValue.videoList.splice(itemIdx, 1)
      if(state.scenes[pidx].elements[eidx].propsValue.videoList.length<=0){
        mutations.resetElementZIndex(state,{type: 'set0'});
        state.scenes[pidx].elements.splice(eidx, 1);
        state.currElementUUID = '';
      }
    }
  },
  /**
   * 更新页面数据
   * @param {*} data
   */
  updatePageData(state, data) {
    const {
      pageData
    } = state
    state.pageData = { ...pageData,
      ...data
    }
  },
  /**
   * 更新节目数据
   * @param {*} data
   */
  updateProgramData(state, data) {
    mutations.updatePageData(state, {
      id: data.id,
      height: data.height ? data.height : $config.canvasPCHeight,
      width: data.width ? data.width : $config.canvasPCWidth,
      programName: data.programName ? data.programName : '默认名称',
      titlePicUrl: data.titlePicUrl ? data.titlePicUrl : '',
      type: data.type ? data.type : 0
    })
    if (data.element) {
      const _pd = JSON.parse(data.element)
      if (_pd.scenes && _pd.scenes.length) {
        mutations.updateProgramScenes(state, _pd.scenes)
        mutations.setCurrSceneUUID(state, _pd.scenes[0].uuid)
      }
    }
  },
  /**
   * 更新场景
   * @param {*} data
   */
  updateProgramScenes(state, data) {
    state.scenes = cloneDeep(data)
  },
  /**
   * 更新某场景数据
   * @param {*} param1
   */
  upadateScenesValue(state, {
    uuid,
    data
  }) {
    const {
      scenes
    } = state
    const pid = scenes.findIndex(item => (item.uuid === uuid))
    if (pid === -1) {
      return
    }
    const pitem = scenes.find(item => (item.uuid === uuid))
    state.scenes[pid] = { ...pitem,
      ...data
    }
  },
  /**
   * 更新某场景数据
   * @param {*} param1
   */
  upadateScenesDurationValue(state, {
    uuid,
    data
  }) {
    const {
      scenes
    } = state
    const pid = scenes.findIndex(item => (item.uuid === uuid))
    if (pid === -1) {
      return
    }
    const pitem = scenes.find(item => (item.uuid === uuid))
    scenes[pid].name =  data.name;
    scenes[pid].duration =  data.duration;
  },
  /**
   * 更新场景样式
   * @param {*} data
   */
  updateSceneStyle(state, data) {
    if (!getters.hasCurrScene(state) || !Object.keys(data).length) {
      return
    }
    const pidx = getters.currSceneIndex(state)
    let {
      commonStyle
    } = state.scenes[pidx]
    const prop = Object.keys(data)[0]
    switch (prop) {
      case 'backgrondColor':
        commonStyle.backgroundImage = ''
        break
      case 'backgroundImage':
        commonStyle.backgroundColor = ''
        break
    }
    state.scenes[pidx].commonStyle = {
      ...commonStyle,
      ...data
    }
  },
  /**
   * 修改场景自定义属性值
   * @param {*} data
   */
  updateScenePropValue(state, data) {
    if (!getters.hasCurrScene(state) || !Object.keys(data).length) {
      return
    }
    const pidx = getters.currSceneIndex(state)
    const {
      propsValue
    } = state.scenes[pidx]
    state.scenes[pidx].propsValue = {
      ...propsValue,
      ...data
    }
  },
  /**
   * 更新元素样式
   * @param {*} data
   */
  updateElementStyle(state, data) {
//	console.log(state)
//	console.log(data)
//	console.log(data.fontSize)
//	data.fontSize++
// console.log(data.width,data.height)

if(data.width++){
	data.fontSize=data.fontSize+0.2
	}


    if (!getters.hasCurrElement) {
      return
    }
    const pidx = getters.currSceneIndex(state)
    const eidx = getters.currElementIndex(state)
    const {
      commonStyle
    } = state.scenes[pidx].elements[eidx]
    state.scenes[pidx].elements[eidx].commonStyle = {
      ...commonStyle,
      ...data
    }
  },
  /**
   * 修改自定义属性值
   * @param {*} data
   */
  updatePropValue(state, data) {
    if (!getters.hasCurrElement) {
      return
    }
    const pidx = getters.currSceneIndex(state)
    const eidx = getters.currElementIndex(state)
    const {
      propsValue
    } = state.scenes[pidx].elements[eidx]
    state.scenes[pidx].elements[eidx].propsValue = {
      ...propsValue,
      ...data
    }
  },
  updatePropValues(state, data) {
    if (!getters.hasCurrElement) {
      return
    }
    const pidx = getters.currSceneIndex(state)
    if(state.scenes[pidx]){
      if(state.scenes[pidx].elements[0]){
        let list = [];
        state.setCurrElementUUID = state.scenes[pidx].elements[0].uuid;
        state.scenes[pidx].elements.forEach(item=>{
          list.push(item);
        })
        state.scenes[pidx].elements.propsValue = {
          ...{bgAudioList:[list]},
          ...data
        }
      }
    }
  },
  /**
   * 修改value
   * @param {*} data
   */
  updateElementValue(state, data) {
    if (!getters.hasCurrElement) {
      return
    }
    const pidx = getters.currSceneIndex(state)
    const eidx = getters.currElementIndex(state)
    state.scenes[pidx].elements[eidx].value = data
    state.scenes[pidx].elements[eidx].propsValue.value = data
  },
  /**
   * 重置层级
   * @param {*} data
   */
  resetElementZIndex(state, {
    type
  }) {
    const {
      currElementUUID
    } = state
    const pidx = getters.currSceneIndex(state)
    let ap = getters.currScene(state)
    let elem = getters.currElement(state)
    let itemZIndex = elem.commonStyle.zIndex
    let maxIndex = ap.elements.length
    let mminIndex = 1
    const zIndexDirc = {
      layerUp: Math.min(itemZIndex + 1, maxIndex),
      layerDown: Math.max(itemZIndex - 1, mminIndex),
      layerTop: maxIndex,
      layerBottom: mminIndex,
      set0: 0
    }
    if (zIndexDirc[type] === undefined) return
    let currentZIndex = zIndexDirc[type]
    let elems = state.scenes[pidx].elements
    elems = elems.map(item => {
      if (item.uuid === currElementUUID) {
        item.commonStyle.zIndex = currentZIndex
        return item
      }
      // 上面一位zIndex减一
      if (type === 'layerUp' && item.commonStyle.zIndex === currentZIndex) {
        item.commonStyle.zIndex--
      }
      // 下面元素zIdex加一
      if (type === 'layerDown' && item.commonStyle.zIndex === currentZIndex) {
        item.commonStyle.zIndex++
      }
      // 目标元素zIndex 以上的都减一
      if (type === 'layerTop' && item.commonStyle.zIndex > itemZIndex) {
        item.commonStyle.zIndex--
      }
      // 目标元素zIndex以下的都加一
      if ((type === 'layerBottom' || type === 'set0') && item.commonStyle.zIndex < itemZIndex) {
        item.commonStyle.zIndex++
      }
      return item
    })
    state.scenes[pidx].elements = [...elems]
  },
  /**
   * 锁定元素
   */
  toggleLockElment(state) {
    if (!getters.hasCurrElement) {
      return
    }
    const pidx = getters.currSceneIndex(state)
    const eidx = getters.currElementIndex(state)
    let elems = state.scenes[pidx].elements
    const {
      locked = false
    } = elems[eidx]
    elems[eidx].locked = !locked
    state.scenes[pidx].elements = [...elems]
  },
  /**
   * 添加事件
   */
  updateElementEvent(state, data) {
    if (getters.hasCurrElement) {
      const pidx = getters.currSceneIndex(state)
      const eidx = getters.currElementIndex(state)
      let elems = state.scenes[pidx].elements
      if (elems[eidx].events.length) {
        const event = elems[eidx].events[0]
        elems[eidx].events = [{ ...event,
          ...data
        }]
      } else {
        elems[eidx].events = [{ ...data
        }]
      }
      state.scenes[pidx].elements = [...elems]
    }
  },
  /**
   * 删除事件
   * @param {*} idx
   */
  deleteElementEvent(state, idx) {
    if (getters.hasCurrElement) {
      const pidx = getters.currSceneIndex(state)
      const eidx = getters.currElementIndex(state)
      let elems = state.scenes[pidx].elements
      elems[eidx].events.length = 0
      state.scenes[pidx].elements = [...elems]
    }
  },
  /**
   * 添加动画，typeId: 0:入场, 1:加强, 2:离场
   * @param {*} param
   */
  updateElementAnimate(state, {
    typeId,
    value
  }) {
    if (getters.hasCurrElement) {
      const pidx = getters.currSceneIndex(state)
      const eidx = getters.currElementIndex(state)
      let elems = state.scenes[pidx].elements
      elems[eidx].animations = elems[eidx].animations ? [...elems[eidx].animations] : []
      elems[eidx].animations[typeId] = { ...elems[eidx].animations[typeId],
        ...value
      }
      state.scenes[pidx].elements = [...elems]
    }
  },
  /**
   * 删除动画
   * @param {*} param1
   */
  deleteElementAnimate(state, {
    typeId
  }) {
    if (getters.hasCurrElement) {
      const pidx = getters.currSceneIndex(state)
      const eidx = getters.currElementIndex(state)
      let elems = state.scenes[pidx].elements
      let {
        animations
      } = elems[eidx]
      animations = animations ? [...animations] : []
      animations[typeId] = null
      elems[eidx].animations = (animations.filter((item) => {
        return item !== null
      }).sort((a, b) => {
        return a.typeId - b.typeId
      }))
      state.scenes[pidx].elements = [...elems]
    }
  },
  updateSceneCover(state, {
    index,
    coverUrl
  }) {
    if (!state.scenes[index]) {
      return
    }
    state.scenes[index].coverUrl = coverUrl
    if (index === 0) {
      state.pageData.titlePicUrl = coverUrl
    }
  },
  /**
  * 更新场景时间
  * @param {*} param0
  * @param {*} duration
  **/
  updateDurationLen(state,duration,hand){
    const pidx = getters.currSceneIndex(state)
    let timeLenStart = 0;
    let timelenVideo = 0;
    let timelenAudio = 0;
    let timelenImage = 0;
    if(hand){
      state.scenes[pidx].duration = duration.toString();
    }else{
      state.scenes[pidx].elements.forEach(function(item,index){
        let imageTimeLen = 0;
        if(item.elName==='sxc-video'){
          if(item.propsValue.videoList){
            for(let i=0; i<item.propsValue.videoList.length; i++){
              if(item.propsValue.videoList[i]){
                timelenVideo += item.propsValue.videoList[i].duration || 0;
              }
            }
          }
        }
        if(item.elName==='sxc-audio'){
          if(item.propsValue.bgAudioList){
            for(let i=0; i<item.propsValue.bgAudioList.length; i++){
              if(item.propsValue.bgAudioList[i]){
                timelenAudio += item.propsValue.bgAudioList[i].duration || 0;
              }
            }
          }
        }
        if(item.elName==='sxc-image'){
          if(item.propsValue.imageSrcList.length>0){
            for(let i=0; i<item.propsValue.imageSrcList.length; i++){
              if(!item.propsValue.imageSrcList[i].switchType || item.propsValue.imageSrcList[i].switchType===false){
                if(item.propsValue.imageSrcList[i].animateInfo){
                  if(item.propsValue.imageSrcList[i].animateInfo.imgSwitchTime){
                    imageTimeLen += item.propsValue.imageSrcList[i].animateInfo.imgSwitchTime || 2;
                  }
                }else{
                    imageTimeLen += 2;
                }
              }else{
                if(item.propsValue.imageSrcList){
                  if(item.propsValue.imageSrcList[0].animateInfoAll){
                      imageTimeLen += item.propsValue.imageSrcList[0].animateInfoAll.imgSwitchTime;
                  }
                }
              }
            }
          }
        }
        timelenImage = imageTimeLen > timelenImage ? imageTimeLen : timelenImage
      })
      let arr = [timelenVideo,timelenAudio,timelenImage];
      for( let k=0;k<arr.length;k++ ){
        if(arr[k]>timeLenStart){
          timeLenStart = arr[k];
        }
      }
      if(timeLenStart>10){
        state.scenes[pidx].duration = timeLenStart.toString();
      }else{
        state.scenes[pidx].duration = '10';
      }
    }
  },
  /**
  * 更新是否弹窗
  * @param {*} param0
  * @param {*} dialog
  **/
  updateDialogPower(state,dialog){
    state.dialog = dialog;
  },
  /**
  * 更新是否弹窗
  * @param {*} param0
  * @param {*} dialog
  **/
  destroyedState(state){
    state.scenes = []
  }
}

const actions = {

  setUpadateScenesDurationValue({state,commit}, {
    uuid,
    data
  }){
    commit('upadateScenesDurationValue',{uuid,data})
  },
  setDestroyedState({state,commit}){
    commit('destroyedState',state)
  },
  /**
  * 修改场景时间
  * @param {*} param0
  * @param {*} duration
  **/
  setDurationLen({state,commit},duration,hand=false){
    commit('updateDurationLen', duration, hand)
  },
  /**
   * 添加元素
   * @param {*} param0
   * @param {*} elData
   */
  addElement({
    state,
    commit
  }, elData) {
    let ap = getters.currScene(state)
    let data = new ElementModel(elData, {
      zIndex: ap.elements.length + 1
    })
    commit('insertElement', data)
    commit('setCurrElementUUID', data.uuid)
    commit('setCurrAttrPannelIndex', '0')
  },
  //设置背景音乐uuid
  setCurrentElement({
    state,
    commit
  }){
    const pidx = getters.currSceneIndex(state)
    let uuid = '';
    state.scenes[pidx].elements.forEach(item=>{
      if(item.elName==='sxc-audio'){
        uuid = item.uuid
      }
    })
    commit('setCurrElementUUID', uuid);
  },
  //设置直播uuid
  setLiveCurrentElement({
    state,
    commit
  }){
    const pidx = getters.currSceneIndex(state)
    let uuid = '';
    state.scenes[pidx].elements.forEach(item=>{
      if(item.elName==='sxc-live'){
        uuid = item.uuid
      }
    })
    commit('setCurrElementUUID', uuid);
  },
  //设置视频uuid
  setVideoCurrentElement({
    state,
    commit
  }){
    const pidx = getters.currSceneIndex(state)
    let uuid = '';
    state.scenes[pidx].elements.forEach(item=>{
      if(item.elName==='sxc-video'){
        uuid = item.uuid
      }
    })
    commit('setCurrElementUUID', uuid);
  },
  /**
   * 复制元素
   */
  copyElment({
    state,
    commit
  }) {
    let ap = getters.currScene(state)
    let elData = getters.currElement(state)
    let data = new ElementModel({
      ...elData,
      uuid: ''
    }, {
      zIndex: ap.elements.length + 1,
      ...elData.commonStyle
    })
    commit('insertElement', data)
    commit('setCurrElementUUID', data.uuid)
    commit('setCurrAttrPannelIndex', '0')
  },
  /**
   * 删除元素
   */
  deleteElment({
    state,
    commit
  }) {
    const {
      currElementUUID
    } = state
    commit('resetElementZIndex', {
      type: 'set0'
    })
    commit('setCurrElementUUID', '')
    commit('deleteElementById', currElementUUID)
    commit('updateDurationLen' )
  },
  /*
  * 根据id删除文件
  * params id
  */
  deleteVideoElmentItemById({
    state,
    commit
  },id) {
    const {
      currElementUUID
    } = state
    commit('deleteVideoElementItemById', id);
    commit('updateDurationLen' )
  },
  deleteElmentItemById({
    state,
    commit
  },id) {
    const {
      currElementUUID
    } = state
    commit('deleteElementItemById', id);
    commit('updateDurationLen' )
    // commit('resetElementZIndex', {
    //   type: 'set0'
    // })
    // commit('setCurrElementUUID', '')
    // commit('deleteElementItemById', currElementUUID)
  },
  deleteAudioById({
    state,
    commit
  }, id) {
    commit('setCurrElementUUID', id)
    commit('resetElementZIndex', {
      type: 'set0'
    })
    commit('setCurrElementUUID', '')
    commit('deleteElementById', id)
    commit('updateDurationLen' )
  },
  requestScenesSave({
    dispatch,
    state,
    commit
  }, params) {
    const scene = getters.currScene(state)
    const pidx = getters.currSceneIndex(state)
    let scenesName = false;
    state.scenes.forEach(function(item){
      for(let ii=0; ii<state.scenes.length; ii++){
        if(item.name === state.scenes[ii].name && item.uuid !== state.scenes[ii].uuid){
          scenesName = true;
        }
      }
    })
    if(scenesName){
      Message.error("场景名重复，保存失败！",5);
      return false;
    }
    if (pidx === -1) {
      return
    }
    if (scene) {
      if (params.cmd === 'add') {
        dispatch('addScenes')
      } else if (params.cmd === 'copy') {
        dispatch('copyScenes', params.scene)
      } else if (params.cmd === 'save') {
        commit('setCurrSceneUUID', state.scenes[pidx].uuid)
      }
      dispatch('postScreenShots', {
        file: params.file,
        path: scene.coverUrl ? scene.coverUrl : ''
      }).then(coverUrl => {
        commit('updateSceneCover', {
          index: pidx,
          coverUrl
        });
        dispatch('saveProgram');
        /* setTimeout(() => {
          if (params.cmd === 'add') {
            dispatch('addScenes')
          } else if (params.cmd === 'copy') {
            dispatch('copyScenes', params.scene)
          } else if (params.cmd === 'change') {
            commit('setCurrSceneUUID', params.uuid)
          }
        }, 60) */
      })
    }
  },
  /**
   * 请求更新
   * @param {*} params
   */
  requestScenesChange({
    dispatch,
    state,
    commit
  }, params) {
    const scene = getters.currScene(state)
    const pidx = getters.currSceneIndex(state)
    if (pidx === -1) {
      return
    }
    if (scene) {
      if(!params.dialog){
        commit('updateDialogPower',false)
      }
      if (params.cmd === 'add') {
        dispatch('addScenes')
      } else if (params.cmd === 'copy') {
      	// console.log(params.idx)
        dispatch('copyScenes', params.scene)
      } else if (params.cmd === 'change') {
        commit('setCurrSceneUUID', params.uuid)
      }
      // dispatch('postScreenShots', {
      //   file: params.file,
      //   path: scene.coverUrl ? scene.coverUrl : ''
      // }).then(coverUrl => {
      //   commit('updateSceneCover', {
      //     index: pidx,
      //     coverUrl
      //   });
      //   // dispatch('saveProgram')
      //   /* setTimeout(() => {
      //     if (params.cmd === 'add') {
      //       dispatch('addScenes')
      //     } else if (params.cmd === 'copy') {
      //       dispatch('copyScenes', params.scene)
      //     } else if (params.cmd === 'change') {
      //       commit('setCurrSceneUUID', params.uuid)
      //     }
      //   }, 60) */
      // })
    }
  },
  /**
   * 添加场景
   * @param {*} uuid
   */
  addScenes({
    state,
    commit
  }, uuid) {
    const {
      width,
      height
    } = state.pageData
    let data = new SceneModel({
      name: '场景',
      commonStyle: {
        width,
        height
      }
    })
    let index = 0
    if (uuid) {
      index = state.scenes.findIndex(v => {
        return v.uuid === uuid
      })
    }
    /* else {
          index = state.scenes.length
        } */
    commit('insertScene', {
      data,
      index
    })
    commit('setCurrSceneUUID', data.uuid)
    commit('setCurrAttrPannelIndex', '0')
  },
  /**
   * 复制场景
   * @param {*} data
   */
  copyScenes({
    state,
    commit
  }, data) {
    let newdata = new SceneModel({ ...data,
      uuid: ''
    })
    let index = 0
    commit('insertScene', {
      data: newdata,
      index
    })
    commit('setCurrSceneUUID', newdata.uuid)
    commit('setCurrAttrPannelIndex', '0')
  },
  saveLocal({
    state
  }) {
    const {
      pageData,
      scenes
    } = state
    const {
      id
    } = pageData
    localStorage[`${$config.KEY_PROGRAM_DATA}_${id}`] = JSON.stringify({
      pageData,
      scenes
    })
  },
  getProgramInfo({
    state,
    commit,
    dispatch
  }, id) {
    const token = getToken()
    let data = new FormData()
    data.append('token', token)
    data.append('id', id)
    axios.post(urls.getProgramInfo, data).then(res => {
      if (res && res.program && res.program.id) {
        commit('updateProgramData', res.program)
        setTimeout(() => {
          if (!state.scenes || !state.scenes.length) {
            dispatch('addScenes')
          }
        }, 60)
      }
    })
  },
  /**
   * 另存为，创建节目 + 保存
   */
  saveAsProgram({
    state,
    commit,
    dispatch
  }) {
    axios.post(urls.create).then(res => {
      if (!res.data) {
        return
      }
      commit('updatePageData', {
        id: res.data.id
      })
      // setTimeout(() => {
      //   dispatch('saveProgram')
      // }, 60)
    })
  },
  /**
   * 保存节目
   */
  saveProgram({
    state,
    commit,
    dispatch
  }, msg) {
    const {
      dialog,
      pageData,
      scenes
    } = state
    dispatch('saveLocal')
    return axios.post(urls.saveProgram, JSON.stringify({
        pageData,
        scenes
      })).then(function(response) {
        if (typeof(msg)==='undefined') {
          if (response.msg == "success") {
            Message.success("保存成功！")
          } else {
            Message.error("保存失败！")
          }
        }
        commit('updateDialogPower',true);
      })
      .catch(function(error) {
        if (typeof(msg)==='undefined') {
          Message.error("保存失败！");
        }
      });

  },
  /**
   * 保存场景截图
   */
  postScreenShots({
    state,
    commit
  }, params) {
    let data = new FormData()
    data.append('file', params.file)
    data.append('path', params.path)
    return new Promise((resolve, reject) => {
      axios.post(urls.uploadBase64, data).then(res => {
        if (res.data) {
          resolve(res.data)
        }
      })
    })
  },
  getSceneCover({
    state
  }, id) {
    const {
      scenes
    } = state;
    if (!scenes || !scenes.length) {
      return ''
    }
    const item = scenes.find(v => {
      return v.uuid === id;
    })
    return item && item.coverUrl ? item.coverUrl : ''
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
